<template>
  <div class="community-container">
    <!-- 页面头部 -->
    <div class="community-header">
      <div class="header-content">
        <h1 class="title">钓鱼社区</h1>
        <p class="subtitle">分享你的钓鱼经验，与钓友们交流心得</p>
      </div>
      <el-button type="primary" size="large" @click="showPublishDialog">
          <el-icon><Plus /></el-icon>
        发布帖子
        </el-button>
    </div>

    <!-- 分类导航 -->
    <div class="category-nav">
      <el-radio-group v-model="selectedCategory" size="large" @change="handleCategoryChange">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button label="fishing">钓鱼经验</el-radio-button>
        <el-radio-button label="help">求助问答</el-radio-button>
        <el-radio-button label="tips">技巧分享</el-radio-button>
        <el-radio-button label="general">综合讨论</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索帖子标题或内容..."
        size="large"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
        <template #append>
          <el-button @click="handleSearch" :icon="Search">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- 主体内容区域 -->
    <el-row :gutter="20" class="main-content">
      <el-col :xs="24" :lg="16">
    <!-- 帖子列表 -->
        <div class="posts-container" v-loading="loading">
      <div v-if="posts.length === 0" class="empty-state">
        <el-empty description="暂无帖子，快来发布第一个帖子吧！" />
      </div>

      <el-card v-for="post in posts" :key="post.id" class="post-card" shadow="hover">
        <div class="post-header">
          <div class="user-info">
            <el-avatar :size="40">{{ (post.nickName || post.username || '用户').charAt(0) }}</el-avatar>
            <div class="user-details">
              <div class="username">{{ post.nickName || post.username || '匿名用户' }}</div>
              <div class="post-time">{{ formatTime(post.createTime) }}</div>
          </div>
        </div>
          <el-tag :type="getCategoryType(post.category)" size="small">
            {{ getCategoryName(post.category) }}
          </el-tag>
        </div>

        <div class="post-content" @click="viewPostDetail(post.id)">
          <h3 class="post-title">{{ post.title }}</h3>
          <p class="post-text">{{ post.content }}</p>
          
          <!-- 图片展示 -->
          <div v-if="getImageList(post.images).length > 0" class="post-images">
            <el-image 
              v-for="(img, index) in getImageList(post.images).slice(0, 3)"
              :key="index"
              :src="img" 
              :preview-src-list="getImageList(post.images)"
              fit="cover"
              class="post-image"
              :preview-teleported="true"
              lazy
            >
              <template #loading>
                <div class="image-loading">
                  <el-icon class="is-loading"><Loading /></el-icon>
          </div>
              </template>
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>加载失败</span>
        </div>
              </template>
            </el-image>
            <div v-if="getImageList(post.images).length > 3" class="more-images">
              +{{ getImageList(post.images).length - 3 }}
            </div>
          </div>
        </div>

        <div class="post-footer">
          <div class="post-stats">
            <span><el-icon><View /></el-icon> {{ post.viewCount || 0 }}</span>
            <span><el-icon><ChatDotRound /></el-icon> {{ post.commentCount || 0 }}</span>
          </div>
          <div class="post-actions">
            <el-button 
              :type="post.isLiked ? 'warning' : 'default'"
              size="small" 
              @click.stop="toggleLike(post)"
              :loading="post.liking"
            >
              <el-icon><component :is="post.isLiked ? StarFilled : Star" /></el-icon>
              {{ post.likeCount || 0 }}
            </el-button>
            <el-button size="small" @click.stop="viewPostDetail(post.id)">
              查看详情
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
        <div v-if="total > 0" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
      </el-col>

      <!-- 右侧热门帖子 -->
      <el-col :xs="24" :lg="8">
        <div class="sidebar-sticky">
          <el-card class="hot-posts-card" shadow="hover">
            <template #header>
              <div class="hot-header">
                <el-icon color="#f56c6c"><TrendCharts /></el-icon>
                <span>热门帖子</span>
              </div>
            </template>
            <div v-loading="hotPostsLoading" class="hot-posts-list">
              <div 
                v-for="(hotPost, index) in hotPosts" 
                :key="hotPost.id" 
                class="hot-post-item"
                @click="viewPostDetail(hotPost.id)"
              >
                <div class="hot-rank" :class="`rank-${index + 1}`">{{ index + 1 }}</div>
                <div class="hot-post-info">
                  <div class="hot-post-title">{{ hotPost.title }}</div>
                  <div class="hot-post-stats">
                    <span><el-icon><View /></el-icon> {{ hotPost.viewCount }}</span>
                    <span><el-icon><Star /></el-icon> {{ hotPost.likeCount }}</span>
                  </div>
                </div>
              </div>
              <div v-if="hotPosts.length === 0" class="no-hot-posts">
                暂无热门帖子
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    
    <!-- 发布帖子对话框 -->
    <el-dialog
      v-model="publishDialogVisible"
      title="发布新帖子"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="postForm" :rules="postRules" ref="postFormRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="请输入帖子标题"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select v-model="postForm.category" placeholder="请选择分类">
            <el-option label="钓鱼经验" value="fishing" />
            <el-option label="求助问答" value="help" />
            <el-option label="技巧分享" value="tips" />
            <el-option label="综合讨论" value="general" />
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="postForm.content" 
            type="textarea" 
            :rows="6"
            placeholder="分享你的钓鱼经验..."
            maxlength="5000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="图片">
          <el-upload
            v-model:file-list="fileList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            accept="image/*"
            multiple
            :limit="9"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">最多上传9张图片，支持jpg、png格式</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="publishDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePublishPost" :loading="publishing">
          发布
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { postAPI, productAPI } from '@/api'
import { Plus, Search, View, ChatDotRound, Star, StarFilled, Loading, Picture, TrendCharts } from '@element-plus/icons-vue'

    const router = useRouter()
    
    // 响应式数据
    const loading = ref(false)
const publishing = ref(false)
const hotPostsLoading = ref(false)
    const posts = ref([])
const hotPosts = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
const selectedCategory = ref('')
    const searchKeyword = ref('')
const publishDialogVisible = ref(false)
    const postFormRef = ref()
const fileList = ref([])
    
// 帖子表单
    const postForm = reactive({
      title: '',
      content: '',
      category: 'general',
  images: null
    })
    
// 表单验证规则
    const postRules = {
  title: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' },
    { min: 1, max: 255, message: '标题长度在1-255个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择帖子分类', trigger: 'change' }
  ]
}

// 获取当前用户ID
const getCurrentUserId = () => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const info = JSON.parse(userInfoStr)
      if (info && (info.userId || info.user_id)) {
        return info.userId || info.user_id
      }
    }
  } catch {}
  
  // 从JWT token中获取用户ID作为备用
  try {
    const token = localStorage.getItem('token') || localStorage.getItem('authToken')
    if (token && token.includes('.')) {
      const payload = JSON.parse(atob(token.split('.')[1] || ''))
      if (payload && (payload.userId || payload.user_id || payload.uid || payload.id)) {
        return payload.userId || payload.user_id || payload.uid || payload.id
      }
    }
  } catch {}
  
  return null
}

// 用户点赞状态管理（按用户ID分组）
const getLikedPosts = () => {
  try {
    const userId = getCurrentUserId()
    if (!userId) return []
    
    const likedPostsData = localStorage.getItem('likedPosts')
    if (!likedPostsData) return []
    
    const allLikedPosts = JSON.parse(likedPostsData)
    
    // 检查是否是旧格式（直接存储数组）
    if (Array.isArray(allLikedPosts)) {
      console.warn('检测到旧格式点赞数据，正在迁移...')
      // 迁移旧数据到新格式
      const newFormat = {}
      newFormat[userId] = allLikedPosts
      localStorage.setItem('likedPosts', JSON.stringify(newFormat))
      return allLikedPosts
    }
    
    // 新格式：按用户ID分组
    const userLikedPosts = allLikedPosts[userId]
    
    // 确保返回的是数组（undefined是正常的初始状态）
    if (Array.isArray(userLikedPosts)) {
      return userLikedPosts
    } else {
      // 首次使用时userLikedPosts为undefined是正常的，不需要警告
      return []
    }
  } catch (error) {
    console.error('获取点赞状态失败:', error)
    return []
  }
}

const saveLikedPosts = (likedPosts) => {
  try {
    const userId = getCurrentUserId()
    if (!userId) return
    
    const likedPostsData = localStorage.getItem('likedPosts')
    const allLikedPosts = likedPostsData ? JSON.parse(likedPostsData) : {}
    allLikedPosts[userId] = likedPosts
    localStorage.setItem('likedPosts', JSON.stringify(allLikedPosts))
  } catch (error) {
    console.error('保存点赞状态失败')
  }
}

const isPostLiked = (postId) => {
  const likedPosts = getLikedPosts()
  // 确保 likedPosts 是数组
  if (!Array.isArray(likedPosts)) {
    console.warn('likedPosts 不是数组:', likedPosts)
    return false
  }
  return likedPosts.includes(postId)
}

// 图片处理 - 参考商城的 parseCoverList 函数
const getImageList = (images) => {
  // 如果为空，返回空数组
  if (!images) return []
  
  // 如果已经是数组，过滤后返回
  if (Array.isArray(images)) {
    // 检查数组第一个元素是否是对象（包含successUrls）
    if (images.length > 0 && images[0] && typeof images[0] === 'object' && images[0].successUrls) {
      return images[0].successUrls.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
    }
    return images.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
  }
  
  // 如果是字符串，尝试解析
  if (typeof images === 'string') {
    // 如果是空字符串，返回空数组
    if (!images.trim()) {
      return []
    }
    
    // 如果看起来像单个URL（以http开头），包装成数组
    if (images.startsWith('http')) {
      return [images]
    }
    
    // 尝试解析JSON字符串
    try {
      const parsed = JSON.parse(images)
      
      // 如果解析结果是数组
      if (Array.isArray(parsed)) {
        // 检查是否是 [{successUrls: [...]}] 格式
        if (parsed.length > 0 && parsed[0] && typeof parsed[0] === 'object' && parsed[0].successUrls) {
          return parsed[0].successUrls.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
        }
        // 普通URL数组
        return parsed.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
      }
      
      // 如果解析结果是对象且包含successUrls
      if (parsed && typeof parsed === 'object' && parsed.successUrls && Array.isArray(parsed.successUrls)) {
        return parsed.successUrls.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
      }
      
      // 如果解析结果是单个URL字符串
      if (typeof parsed === 'string' && parsed) {
        return [parsed]
      }
      
      return []
    } catch (error) {
      console.warn('解析图片列表失败:', images)
      return []
    }
  }
  
  // 其他情况返回空数组
  return []
}

    
    // 获取帖子列表
    const fetchPosts = async () => {
      try {
        loading.value = true
    console.log('开始获取帖子列表...')
        let response
        
        if (searchKeyword.value.trim()) {
          // 搜索帖子
      console.log('搜索帖子:', searchKeyword.value)
          response = await postAPI.searchPosts({
            keyword: searchKeyword.value,
            page: currentPage.value,
            size: pageSize.value
          })
    } else if (selectedCategory.value) {
      // 按分类获取
      console.log('按分类获取帖子:', selectedCategory.value)
          response = await postAPI.getPostsByCategory(selectedCategory.value, {
            page: currentPage.value,
            size: pageSize.value
          })
        } else {
      // 获取全部帖子
      console.log('获取全部帖子')
          response = await postAPI.getPostList({
            page: currentPage.value,
            size: pageSize.value
          })
        }
    
    console.log('API响应:', response)
        
        if (response.code === 0) {
      posts.value = (response.data.posts || []).map(post => ({
        ...post,
        isLiked: isPostLiked(post.id),
        liking: false
      }))
          total.value = response.data.total || 0
        } else {
      console.error('获取帖子列表失败:', response)
          ElMessage.error(response.message || '获取帖子列表失败')
        }
      } catch (error) {
    console.error('获取帖子列表异常:', error)
    ElMessage.error('获取帖子列表失败: ' + (error.message || '网络错误'))
      } finally {
        loading.value = false
      }
    }
    
// 发布帖子对话框
const showPublishDialog = () => {
      const token = localStorage.getItem('token')
      if (!token) {
    ElMessageBox.confirm(
      '发布帖子需要登录后才能使用，是否前往登录页面？',
      '需要登录',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'info',
        showClose: false
      }
    ).then(() => {
        router.push('/userLogin')
    }).catch(() => {
      // 用户取消，不做任何操作
    })
        return
      }
  publishDialogVisible.value = true
}

// 上传图片
const uploadImages = async (files) => {
  if (files.length === 0) return []
  
  try {
    // 收集所有的raw文件
    const rawFiles = files.map(file => file.raw).filter(f => f)
    if (rawFiles.length === 0) {
      return []
    }
    
    const response = await productAPI.uploadImages(rawFiles)
    if (response.code === 0 && response.data) {
      // 处理后端返回的数据格式
      // 后端可能返回: { successUrls: [...], ... } 或直接返回 [...]
      if (response.data.successUrls && Array.isArray(response.data.successUrls)) {
        return response.data.successUrls
      }
      // 兼容直接返回数组的情况
      if (Array.isArray(response.data)) {
        return response.data
      }
      // 兼容返回单个URL的情况
      if (typeof response.data === 'string') {
        return [response.data]
      }
    }
    return []
  } catch (error) {
    console.error('图片上传失败:', error)
    throw new Error('图片上传失败')
  }
}

// 发布帖子
const handlePublishPost = async () => {
      try {
        await postFormRef.value.validate()
        
    publishing.value = true
    
    // 上传图片
    let imageUrls = []
    if (fileList.value.length > 0) {
      imageUrls = await uploadImages(fileList.value)
      if (imageUrls.length === 0) {
        ElMessage.error('图片上传失败')
        publishing.value = false
        return
      }
    }
    
    // 提交帖子
        const postData = {
          title: postForm.title,
          content: postForm.content,
          category: postForm.category,
      images: imageUrls.length > 0 ? JSON.stringify(imageUrls) : null
        }
        
        const response = await postAPI.createPost(postData)
    
        if (response.code === 0) {
      ElMessage.success('帖子发布成功！')
      publishDialogVisible.value = false
      resetForm()
      currentPage.value = 1
      await fetchPosts()
        } else {
          ElMessage.error(response.message || '发布失败')
        }
      } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    publishing.value = false
      }
    }
    
    // 重置表单
const resetForm = () => {
      postForm.title = ''
      postForm.content = ''
      postForm.category = 'general'
  fileList.value = []
  postFormRef.value?.resetFields()
}

// 文件变化
const handleFileChange = (file, files) => {
  fileList.value = files
}

const handleFileRemove = (file, files) => {
  fileList.value = files
    }
    
    // 查看帖子详情
const viewPostDetail = (postId) => {
  router.push(`/community/post/${postId}`)
    }
    
    // 点赞/取消点赞
    const toggleLike = async (post) => {
      const token = localStorage.getItem('token')
  if (!token) {
    ElMessageBox.confirm(
      '点赞功能需要登录后才能使用，是否前往登录页面？',
      '需要登录',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'info',
        showClose: false
      }
    ).then(() => {
        router.push('/userLogin')
    }).catch(() => {
      // 用户取消，不做任何操作
    })
        return
      }
      
  if (post.liking) return
  
  try {
        post.liking = true
        
        const response = await postAPI.likePost(post.id)
    
        if (response.code === 0) {
          // 切换点赞状态
      post.isLiked = !post.isLiked
      
      if (post.isLiked) {
        // 点赞
            post.likeCount = (post.likeCount || 0) + 1
        const likedPosts = getLikedPosts()
        if (!likedPosts.includes(post.id)) {
          likedPosts.push(post.id)
          saveLikedPosts(likedPosts)
        }
            ElMessage.success('点赞成功')
          } else {
        // 取消点赞
            post.likeCount = Math.max(0, (post.likeCount || 0) - 1)
        const likedPosts = getLikedPosts()
        const index = likedPosts.indexOf(post.id)
        if (index > -1) {
          likedPosts.splice(index, 1)
          saveLikedPosts(likedPosts)
        }
            ElMessage.success('取消点赞')
          }
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        post.liking = false
      }
    }
    
// 分类变化
    const handleCategoryChange = () => {
      currentPage.value = 1
  searchKeyword.value = ''
      fetchPosts()
    }
    
// 搜索
    const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
      currentPage.value = 1
  selectedCategory.value = ''
      fetchPosts()
    }
    
// 分页
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      fetchPosts()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchPosts()
    }
    
// 工具函数
    const formatTime = (time) => {
      if (!time) return ''
      const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  
  if (diff < minute) return '刚刚'
  if (diff < hour) return `${Math.floor(diff / minute)}分钟前`
  if (diff < day) return `${Math.floor(diff / hour)}小时前`
  if (diff < 7 * day) return `${Math.floor(diff / day)}天前`
  
  return date.toLocaleDateString('zh-CN')
    }
    
    const getCategoryName = (category) => {
      const categoryMap = {
    fishing: '钓鱼经验',
    help: '求助问答',
    tips: '技巧分享',
    general: '综合讨论'
      }
      return categoryMap[category] || '其他'
    }
    
    const getCategoryType = (category) => {
      const typeMap = {
    fishing: 'primary',
    help: 'warning',
    tips: 'success',
    general: 'info'
      }
      return typeMap[category] || 'info'
    }
    
// 获取热门帖子
const fetchHotPosts = async () => {
  try {
    hotPostsLoading.value = true
    const response = await postAPI.getHotPosts(5)
        
        if (response.code === 0) {
      hotPosts.value = response.data || []
        }
      } catch (error) {
    console.error('获取热门帖子失败')
  } finally {
    hotPostsLoading.value = false
      }
    }
    
// 页面加载
    onMounted(() => {
  // 防止因遗留的弹窗/预览遮罩导致页面无法滚动
  try {
    document.body.classList.remove('el-popup-parent--hidden')
    if (document.body.style.overflow === 'hidden') {
      document.body.style.overflow = ''
    }
  } catch {}

      fetchPosts()
  fetchHotPosts()
})
</script>

<style scoped>
.community-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.community-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
}

.header-content .title {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 600;
}

.header-content .subtitle {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.category-nav {
  margin-bottom: 24px;
  text-align: center;
}

.search-bar {
  margin-bottom: 24px;
}

.main-content {
  margin-top: 24px;
}

.sidebar-sticky {
  position: sticky;
  top: 24px;
  max-height: calc(100vh - 24px);
  overflow: hidden;
}

.hot-posts-card {
  border-radius: 12px;
}

.hot-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
}

.hot-posts-list {
  min-height: 200px;
  max-height: 400px;
  overflow-y: auto;
  overscroll-behavior: contain;
}

.hot-post-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.hot-post-item:hover {
  background: #f0f0f0;
  transform: translateX(4px);
}

.hot-rank {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  font-weight: 600;
  font-size: 14px;
  background: #909399;
  color: white;
  flex-shrink: 0;
}

.hot-rank.rank-1 {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.hot-rank.rank-2 {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.hot-rank.rank-3 {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.hot-post-info {
  flex: 1;
  min-width: 0;
}

.hot-post-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hot-post-stats {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.hot-post-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.no-hot-posts {
  text-align: center;
  color: #909399;
  padding: 40px 0;
  font-size: 14px;
}

.posts-container {
  min-height: 400px;
}

.empty-state {
  padding: 60px 0;
}

.post-card {
  margin-bottom: 20px;
  border-radius: 12px;
  transition: all 0.3s;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }
  
  .post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
    gap: 12px;
  }
  
.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 600;
  color: #303133;
}

.post-time {
  font-size: 12px;
  color: #909399;
}

.post-content {
  cursor: pointer;
  margin-bottom: 16px;
}

.post-title {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1.5;
}

.post-text {
  margin: 0 0 12px 0;
  color: #606266;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-images {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 12px;
}

.post-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  cursor: pointer;
}

.more-images {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 8px;
  color: #909399;
  font-size: 18px;
  font-weight: 600;
}

.image-loading,
.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.image-error {
  gap: 8px;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}

.post-stats {
  display: flex;
  gap: 20px;
  color: #909399;
  font-size: 14px;
}

.post-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.post-actions {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .community-container {
    padding: 12px;
  }

  .community-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .header-content .title {
    font-size: 24px;
  }

  .post-card {
    margin-bottom: 12px;
  }

  .post-image {
    width: 100px;
    height: 100px;
  }

  .more-images {
    width: 100px;
    height: 100px;
  }
}
</style>
